<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\ApiController;
use app\api\model\SupplyUser;
use app\api\service\UserToken;
use NieGe\Tool;

class Token extends ApiController
{
    /**
     * 获取用户令牌
     * @MethodAuthor: 聂哥
     * @Date: 2023-03-11 00:47:14
     */
    public function create($code)
    {
        $wxLoginUrl = sprintf(
            config('wx.login_url'),
            config('wx.app_id'), 
            config('wx.app_secret'), 
            $code
        );
        $result = Tool::https_request($wxLoginUrl);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)){
            throw new \think\Exception('微信内部错误');
        }
        if (array_key_exists('errcode', $wxResult)){
            throw new \think\Exception('微信错误' . $wxResult['errmsg']);
        }
        $openid = $wxResult['openid'];
        $wxResult['uid'] = SupplyUser::getUidByOpenid($openid);
        $token = UserToken::generateAccessToken($wxResult);
        return [
          'token'      => $token,
          'expire_time' => config('token.expire_time')
        ];
    }

    public function verify()
    {
        
    }
}